package com.whty.fastdfs;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.whty.mariotools.IdGenerator;





/**
 * <p>Description: FastDFS文件上传下载包装类</p>
 * <p>Copyright: Copyright (c) 2017</p>
 *
 * @author fuweidong
 * @version 1.0
 * @date 2017/11/16
 */
@Component
public class FastDFSClientWrapper {

    private final Logger logger = LoggerFactory.getLogger(FastDFSClientWrapper.class);

    @Autowired
    private FastFileStorageClient storageClient;

    /*@Autowired
    private AppConfig appConfig;   // 项目参数配置
  
*/
    
   public void testupload() throws Exception{
	   File file=new File("F:\\05-zoopkeeper\\聚联18年1月KPI考核_秦晨晖.xlsx");
	   System.out.println(uploadFile(file));
   }
    
    
    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public String uploadFile(File file) throws IOException { //MultipartFile file
    	InputStream input = new FileInputStream(file) ;
    	StorePath storePath = storageClient.uploadFile(input , file.length() , FilenameUtils.getExtension(file.getName()) , null);
        //StorePath storePath = storageClient.uploadFile(  file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()) , null);
    	input.close();
    	return getResAccessUrl(storePath);
    }
    
    
    public String uploadFileByBase64(Map<String,Object> map) throws IOException { //MultipartFile file
  
    	StorePath storePath = storageClient.uploadFile((InputStream) map.get("fileInputStream") ,Long.valueOf( map.get("fileLength").toString()), (String) map.get("extension"), null);
        //StorePath storePath = storageClient.uploadFile(  file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()) , null);
        return getResAccessUrl(storePath);
    }
    
    public String uploadFileByMulti(MultipartFile file) throws IOException { //MultipartFile file
    	  
    	StorePath storePath = storageClient.uploadFile(file.getInputStream() ,file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()), null);
        //StorePath storePath = storageClient.uploadFile(  file.getInputStream(), file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()) , null);
        return getResAccessUrl(storePath);
    }

    /**
     * 将一段字符串生成一个文件上传
     * @param content 文件内容
     * @param fileExtension
     * @return
     */
    public String uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
        return getResAccessUrl(storePath);
    }

    // 封装图片完整URL地址
    private String getResAccessUrl(StorePath storePath) {
        /*String fileUrl = AppConstants.HTTP_PRODOCOL + appConfig.getResHost()
                + ":" + appConfig.getFdfsStoragePort() + "/" + storePath.getFullPath();
        return fileUrl;*/
        return storePath.getFullPath();
    }

    /**
     * 删除文件
     * @param fileUrl 文件访问地址
     * @return
     */
    public void deleteFile(String fileUrl) {
        if (StringUtils.isEmpty(fileUrl)) {
            return;
        }
        try {
            StorePath storePath = StorePath.praseFromUrl(fileUrl);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            logger.warn(e.getMessage());
        }
    }
    
    public void downloadFile(String groupName,String ser_path){
    	storageClient.downloadFile(groupName, ser_path, null);
    }
    
    
    public File downloadFile(String fileUrl){
    	File uploadFile = new File(IdGenerator.getRanId() + ".jpeg");
    	BufferedInputStream bis = null;
        try {
          URL url = new URL(fileUrl);
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.setDoInput(true);
          conn.setRequestMethod("GET");
          bis = new BufferedInputStream(conn.getInputStream());
        } catch (Exception e) {
        	e.printStackTrace();
        }
    	
    	try {
            BufferedOutputStream fos = new BufferedOutputStream( new FileOutputStream(uploadFile));
            byte[] buf = new byte[8096];
            int size = 0;
            while ((size = bis.read(buf)) != -1)
              fos.write(buf, 0, size);
            fos.close();
            bis.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    	return uploadFile ;
    }
}